<?php
namespace Tsnews\Controller;
use Think\Controller;
class IndexController extends Controller{
    public function index(){
        if(isset($_GET['code'])){
            $code = $_GET['code'];
            $corpid = C('CORPID');
            $secret = C('SECRET');
            $access_token = tsnewsgetaccesstoken($corpid,$secret); //获取access_token
            $data = $this->signature($access_token);  //获取jssdk签名配置
            $info = $this->group_ticket($access_token); //获取通讯录选人签名配置
            $userID = $this->getuserid($code,$access_token); //获取userID
            $list = $this->getzbm($userID);  //获取当前userid的所有子部门
            //dump($list);exit;
            $zbm_user_list = $this->getzbm_user($userID);//获取当前userid的所有子部门的成员
            //dump($zbm_user_list);exit;
            $this->assign(array(      //jssdk签名配置
                'appid' => $corpid,
                'timestamp' => $data['timestamp'],
                'nonceStr' => $data['nonceStr'],
                'signature' => $data['signature'],
            ));
            $this->assign(array(     //通讯录选人签名配置
                'group_id' => $info['group_id'],
                'groputime' => $info['timestamp'],
                'groupnonceStr' => $info['nonceStr'],
                'groupsignature' => $info['signature'],
            ));
            $this->assign(array(
                'userid' => json_encode($userID), //当前userid
                'zbmid' => $list['zbm'],  //当前userid的子部门ID 打开通讯录使用
                'zbmids' => json_encode($list['zbm']),  //当前userid的子部门ID  选部门筛选使用
                'userinfo' => json_encode($list['data']), //所有成员的详细信息
                'z_user' => $zbm_user_list['zbm_user_str'], //当前userid可选的userid列表
                'zbmuser' => json_encode($zbm_user_list['zbm_user']) //当前userid的所有子部门的成员
            ));
            $this->display();
        }else{
            echo 'no code';
        }
    }

    /**
     * 获取userID
     * @param $code
     * @param $access_token
     * @return mixed
     */
    public function getuserid($code,$access_token){
        $getuseridURL = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$access_token}&code={$code}";
        $userid = json_decode(https_request($getuseridURL),true)['UserId'];
        return $userid;
    }

    /**
     * jssdk签名配置
     * @param $accesstoken
     * @return array
     */
    public function signature($accesstoken){
        $ticket = tsnewsget_ticket($accesstoken);
        $noncestr =md5(time());
        $time = time();
        $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $str1 = "jsapi_ticket={$ticket}&noncestr={$noncestr}&timestamp={$time}&url={$url}";
        $singature = sha1($str1);
        return array(
            'timestamp' => $time,
            'nonceStr' => $noncestr,
            'signature' => $singature,
        );
    }

    /**
     * 通讯录选人签名配置
     * @param $accesstoken
     * @return array
     */
    public function group_ticket($accesstoken){
        $data = getgroup_ticket($accesstoken);
        $info = explode(',',$data);
        $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $noncestr =md5(time());
        $time = time();
        $str1 = "group_ticket={$info[0]}&noncestr={$noncestr}&timestamp={$time}&url={$url}";
        $singature = sha1($str1);
        return array(
            'timestamp' => $time,
            'nonceStr' => $noncestr,
            'signature' => $singature,
            'ticket' => $info[0],
            'group_id' => $info[1]
        );
    }

   //发送年报正文消息
    public function sendMessage(){
        $userid = I('post.userid');
        $user_list = I('post.user_list');
        $dep_list = I('post.dep_list');
        $type = I('post.person_type');
        $content = I('post.content');
        $corpid = C('CORPID');
        $secret = C('SECRET');
        $appurl = C('RPOJECT_URL');

        $access_token = tsnewsgetaccesstoken($corpid,$secret); //获取access_token
        $redis = linkredis();
        $userinfo = unserialize($redis->get($corpid .'_user_info'));
        $depinfo= unserialize($redis->get($corpid .'_dep_info'));
        if($type == 2){
            //是全部成员,把缓存的当前userid的所有子部门成员全部取出
            if(!$list = $userinfo[$userid]['zbm_user']){
                $this->error('抱歉,您的子部门目前还没有成员!');
            }else{
                $userlist = str_replace(',','|',$list);
            }
        }else{
            if($dep_list && $user_list){  //同时提交部门和成员
                $dep_list = explode(',',$dep_list);
                $user_str = '';
                foreach($dep_list as $k=>$v){
                    if($depinfo[$v]['dep_user']) {
                        $user_str .= $depinfo[$v]['dep_user'] . ',';
                    }
                }
                $dep_user = trim($user_str,','); //得到提交的部门下的成员,去掉,
                $userlist = trim($user_list .','.$dep_user,',');  //把提交的部门ID下的成员和添加的成员拼接
                $userlist = implode('|',array_unique(explode(',',$userlist)));
            }else if($dep_list){   //只提交部门
                $dep_list = explode(',',$dep_list);
                $user_str = '';
                foreach($dep_list as $k=>$v){
                    if($depinfo[$v]['dep_user']) {
                        $user_str .= $depinfo[$v]['dep_user'] . ',';
                    }
                }
                $user_str = trim($user_str,',');
                if(!$user_str){
                    $this->error('抱歉,没有符合发送消息的成员,请重新选择!');
                }else{
                    $userlist = implode('|',array_unique(explode(',',$user_str)));
                }
            }else if($user_list){  //只提交成员
                $userlist = str_replace(',','|',$user_list);
            }
        }
        //dump($userlist);
        $content = urlencode($content);//把正文放到URL一起带过去
        $username = $userinfo[$userid]['name'];//获取发件人
       // dump($username);exit;
        $articles[] = array(
            'title' => urlencode('年报催报'),
            'description' => urlencode('来自'.$username.'的年报催报'),
            'url' => "{$appurl}Tsnews/Index/nbnews//cachename/{$content}",
            'picurl' => ''
        );

        $articles = array('articles' => $articles);
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$access_token";
        $post = array(
            'touser'   => $userlist,
            'toparty'  => '',
            'totag'    => '',
            'msgtype'  => 'news',
            'agentid'  => C('YYID'),
            'news'     => $articles
        );
        $post = urldecode(json_encode($post));
        //发送请求
        //dump($post);exit;
        $res = json_decode(https_request($url, $post),true);
        //检测消息发送是否成功
        if($res['errorcode']==0){
            $this->assign('str','发送成功!');
            $this->display('tishi');
        }else{
            $this -> error('发送失败!');
        }
    }

    /**
     * 取出当前userid的所有子部门ID
     * @param $userid
     * @return mixed
     */
    public function getzbm($userid){
        $corpid = C('CORPID');
        $redis = linkredis();
        $data = unserialize($redis->get($corpid .'_user_info'));
        $keys = array_keys($data);
        if(!$data || !in_array($userid,$keys)){
            A('Cache')->getuserinfo();
            $data = unserialize($redis->get($corpid .'_user_info'));
        }
        return  array(
            'zbm' => $data[$userid]['zbm_id'],
            'data' => $data
            );
    }

    /**
     * 获取当前userid的所有子部门成员
     * @param $userid
     * @return array
     */
    public function getzbm_user($userid){
        $corpid = C('CORPID');
        $redis = linkredis();
        $data = unserialize($redis->get($corpid.'_user_info'));

        $zbm_user = explode(',',$data[$userid]['zbm_user']);
        $str = '';
        foreach($zbm_user as $k=>$v){
            $str .= "'".$v."'".',';
        }
        return array(
            'zbm_user_str' => trim($str,','),
            'zbm_user' => $data[$userid]['zbm_user']
        );

    }

    //年报显示
    public function nbnews(){
        $cachename = I('get.cachename');
        //$content = unserialize(S($cachename));
        $content = urldecode($cachename);
        //dump($content);exit;
        $time = date('Y-m-d',time());
        $this->assign(array(
            'time' => $time,
            'content' => $content
        ));
        $this->display();
    }

    public function aaa(){
        $redis = linkredis();
        dump(unserialize($redis->get('wx354598b372f7261a_dep_info')));
        dump(unserialize($redis->get('wx354598b372f7261a_user_info')));
//        $redis->del('groupid_ticket');
//        $redis->del('tsnews_accesstoken');
//        $redis->del('wx354598b372f7261a_zbm_user');
//        $redis->del('wx354598b372f7261a_info');
        dump($redis->keys('*'));
    }
}